package com.dhy.util;


import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *     文件读取工具类
 * </p>
 * @author 大忽悠
 * @create 2022/7/6 8:39
 */
public class FileReaderUtil {
    /**
     * 线程池----用于并发读取文件
     */
    private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(10);
    /**
     * 换行符
     */
    private static final String SEPARATOR =System.lineSeparator();

    /**
     * 跳到新的一行去读取
     */
    public static void skipToNewLine(RandomAccessFile accessFile) throws IOException {
        int len = SEPARATOR.getBytes(StandardCharsets.UTF_8).length;
        byte[] targetByte = new byte[len];
        accessFile.read(targetByte,0,len);
        if(!new String(targetByte).equals(SEPARATOR)){
            accessFile.readLine();
        }
    }

    /**
     * 读取分片数据
     */
    public static List<String> concurrentReadIndex(RandomAccessFile accessFile, Long num) throws IOException {
        List<String> res=new ArrayList<>();
        while(num>0){
            String readLine = accessFile.readLine();
            res.add(readLine);
            num-=readLine.getBytes().length;
        }
        return res;
    }
}
